package cn.acewill.yxd.yunxundian.ui;


import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;

import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.acewill.yxd.yunxundian.Api.UpdateApi;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.adapter.MainPageFragmentAdapter;
import cn.acewill.yxd.yunxundian.componet.NetWorkStateReceiver;
import cn.acewill.yxd.yunxundian.model.Employee;
import cn.acewill.yxd.yunxundian.pubClass.OKHttpUICallback;
import cn.acewill.yxd.yunxundian.pubClass.OkHttpManger;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.user.FirstPageFragment;
import cn.acewill.yxd.yunxundian.ui.user.MainMessageFragment;
import cn.acewill.yxd.yunxundian.ui.user.MyInfoFragment;
import cn.acewill.yxd.yunxundian.ui.user.MyNotifictionService;
import cn.acewill.yxd.yunxundian.utils.CacheActivity;
import cn.acewill.yxd.yunxundian.utils.MaterialDialogUtils;
import cn.acewill.yxd.yunxundian.utils.UpdateUtils;
import cn.finalteam.toolsfinal.adapter.FragmentAdapter;
import okhttp3.Call;

/**
 * Created by AAA on 2017/3/30.
 */
public class MainActivity extends FragmentActivity {

    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    private CheckBox mainPage,myMessage,myInfo;
//    private ImageView under_MyInfo_number;
    public static TextView under_Message_number;
    //private Fragment frags[]={new FirstPageFragment(),new MainMessageFragment(),new MyInfoFragment()};
    public static int id;//登录的用户id
    public static int signId=0;//签到的id
    public static String firstName;
    /*记录时间*/
 //   private long firstTime=0;
    //记录消息的数量,默认空
    public static int messageCount=0;
    public static final String MESSAGE_UNREAD="action_msg_unread";
    private static BroadcastReceiver receiver;
    private static BroadcastReceiver netReceiver;

    private ViewPager vpager;
    //底部颜色的RGB值
    private boolean isfirstLoad = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setStatusBar();
        id = getIntent().getIntExtra("userId", -1);
        firstName=getIntent().getStringExtra("userName");
        isfirstLoad=true;
        initView();
        //防止应用在进程，打开后出现url为空的情况
        if (pubClass.Server_namehzm==null){
            pubClass.seturl(this);
        }
        opservice();
        //注册广播接收者，用于接收消息变动
        registerMessageReceiver();
        registerNetWorkRecevier();
        loadImg.start();
        readVersionData(pubClass.apkVersionInfoUrl);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //防止应用在进程，打开后出现url为空的情况
        if (pubClass.Server_namehzm==null){
            pubClass.seturl(this);
        }

    }
    public void registerMessageReceiver(){
        final IntentFilter filter=new IntentFilter();
        filter.addAction(MESSAGE_UNREAD);
        if (receiver==null){
            receiver= new receiverMsg();
            registerReceiver(receiver,filter);
        }
    }
    public void registerNetWorkRecevier(){
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        if (netReceiver == null){
            netReceiver = new MyNetWorkStateReceiver();
            registerReceiver(netReceiver,filter);
        }
    }

    class MyNetWorkStateReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            //API 23
            if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
                //获取所有网络连接的信息
                Network[] networks = mConnectivityManager.getAllNetworks();
                //用于存放网络连接信息
                StringBuilder sb = new StringBuilder();
                //通过循环将网络信息逐个取出来
                for (int i=0; i < networks.length; i++){
                    //获取ConnectivityManager对象对应的NetworkInfo对象
                    NetworkInfo networkInfo = mConnectivityManager.getNetworkInfo(networks[i]);
                    sb.append(networkInfo.getType() + "|" + networkInfo.isConnected());
                    if (networkInfo!=null&&networkInfo.isConnected()){
                        NetWorkStateReceiver.whetherConnectNetWork = 1;
                        int type = networkInfo.getType();
                        if (type == ConnectivityManager.TYPE_WIFI) {
                            NetWorkStateReceiver.netWorkType =1;
                        } else if (type == ConnectivityManager.TYPE_MOBILE) {
                            NetWorkStateReceiver.netWorkType = 2;
                        }
                    }else{
                        NetWorkStateReceiver.whetherConnectNetWork=0;
                    }
                }
            }else{
                NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
                if (mNetworkInfo!=null&&mNetworkInfo.isConnected()){
                   NetWorkStateReceiver.whetherConnectNetWork=1;
                    int type = mNetworkInfo.getType();
                    if (type == ConnectivityManager.TYPE_WIFI) {
                        NetWorkStateReceiver.netWorkType =1;
                    } else if (type == ConnectivityManager.TYPE_MOBILE) {
                        NetWorkStateReceiver.netWorkType = 2;
                    }
                }else{
                    NetWorkStateReceiver.whetherConnectNetWork=0;
                }
            }

        }
    }


    public void addfragment(){
        List<Fragment> fragmentList=new ArrayList<>();
        fragmentList.add(new FirstPageFragment());
        fragmentList.add(new MainMessageFragment());
        fragmentList.add(new MyInfoFragment());
        FragmentAdapter adapter =new MainPageFragmentAdapter(getSupportFragmentManager(),fragmentList);
        vpager.setAdapter(adapter);
        //设置缓存界面数，较少可行
        vpager.setOffscreenPageLimit(2);
        vpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//                Log.e("position",position+"");
//                Log.e("positionOffset",positionOffset+"");
//                Log.e("positionOffsetPixels",positionOffsetPixels+"");
//                int colordata = Color.rgb(-84,71,151);
//                int bluecolor = Color.rgb(1,156,236);
//                int whitecolor = Color.rgb(85,85,85);
//                int rcolor = (int) (1-(-84*positionOffset))+1;
//                int gcolor = (int) (156-(71*positionOffset))-1;
//                int bcolor = (int) (236-(151*positionOffset))-1;
//                Log.e("positionInt1",rcolor+"");
//                Log.e("positionInt2",gcolor+"");
//                Log.e("positionInt3",bcolor+"");
//                mainPage.setTextColor(Color.rgb(rcolor,gcolor,bcolor));
            }
            @Override
            public void onPageSelected(int position) {
                if (position==0){
                    vpager.setCurrentItem(0,true);
                    mainPage.setChecked(true);
                    myMessage.setChecked(false);
                    myInfo.setChecked(false);
                }else if(position==1){
                    myMessage.setChecked(true);
                    myInfo.setChecked(false);
                    mainPage.setChecked(false);
                    loadUserMassgeCount();
                }else if (position==2){
                    myInfo.setChecked(true);
                    mainPage.setChecked(false);
                    myMessage.setChecked(false);
                }
            }
            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    public void initView(){
        this.under_Message_number=  findViewById(R.id.under_Message_number);
  //      this.under_MyInfo_number=  findViewById(R.id.under_MyInfo_number);
        this.mainPage=  findViewById(R.id.mainPage);
        this.myMessage=  findViewById(R.id.myMessage);
        this.myInfo=  findViewById(R.id.myInfo);
        this.vpager =  findViewById(R.id.viewPager);
        mainPage.setChecked(true);
        addfragment();
        //changeFragment(frags[0]);
    }

    //开启通知服务
    public void opservice(){
        Intent intent =new Intent(this, MyNotifictionService.class);
        startService(intent);
    }

    class receiverMsg extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            int count=intent.getIntExtra("count",0);
            messageCount = messageCount - count;
            under_Message_number.setText(String.valueOf(messageCount));
            if (messageCount>0){
                if (messageCount>=99)under_Message_number.setText(String.valueOf(99));
                else under_Message_number.setVisibility(View.VISIBLE);
            }else{
                under_Message_number.setVisibility(View.GONE);
            }
        }
    }
    Thread loadImg=new Thread(){
        @Override
        public void run() {
            loadUserMassgeCount();
            try {
                Employee employee=db.selector(Employee.class).where("ID","=",id).findFirst();
                if (employee.getEmpImage()!=null){
                    String path= pubClass.pictureSavePath+employee.getEmpImage();
                    File file=new File(path);
                    String singPath=pubClass.downLoadUri+employee.getEmpImage();
                    if (!file.exists()){
                        downloadFile(singPath,path);
                    }
                }
            } catch (DbException e) {
                e.printStackTrace();
            }
        }
    };





    public void onTabClicked(View view){
        switch (view.getId()){
            case R.id.mainPage:
              // changeFragment(frags[0]);
                vpager.setCurrentItem(0,false);
                mainPage.setChecked(true);
                myMessage.setChecked(false);
                myInfo.setChecked(false);
                break;
            case R.id.myMessage:
              //  changeFragment(frags[1]);
                vpager.setCurrentItem(1,false);
                myMessage.setChecked(true);
                myInfo.setChecked(false);
                mainPage.setChecked(false);
                loadUserMassgeCount();
                break;
            case R.id.myInfo:
             //   changeFragment(frags[2]);
                vpager.setCurrentItem(2,false);
                myInfo.setChecked(true);
                mainPage.setChecked(false);
                myMessage.setChecked(false);
                break;
        }
    }

//    public void changeFragment(Fragment tagFragment){
//        FragmentTransaction ft = fragmentManager.beginTransaction();
//        //设置跳转的动画
//        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
////        ft.setCustomAnimations(R.anim.fragment_slide_right_in,R.anim.fragment_slide_right_out);
//        ft.replace(R.id.fragment_container,tagFragment).show(tagFragment).commit();
//    }

    /*返回键的监听*/
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        switch (keyCode){
//            case KeyEvent.KEYCODE_BACK:
//                long secondTime =System.currentTimeMillis();
//                /*大于两秒则不退出*/
//                if (secondTime-firstTime>=2000){
//                    BaseActivity.showToast(this,"再按一次退出程序");
//                    //更新第一次的时间
//                    firstTime=secondTime;
//                    return  true;
//                }else{
//                    System.exit(0);
//                }
//                break;
//        }
//        return super.onKeyDown(keyCode,event);

        if (!mainPage.isChecked()){
       //     changeFragment(frags[0]);
            vpager.setCurrentItem(0,false);
            mainPage.setChecked(true);
            myMessage.setChecked(false);
            myInfo.setChecked(false);

            return false;
        }else {
            //销毁之前开启的activity
            CacheActivity.finishActivity();
            PackageManager pm = getPackageManager();
            ResolveInfo homeInfo =
                    pm.resolveActivity(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME), 0);
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                ActivityInfo ai = homeInfo.activityInfo;
                Intent startIntent = new Intent(Intent.ACTION_MAIN);
                startIntent.addCategory(Intent.CATEGORY_LAUNCHER);
                startIntent.setComponent(new ComponentName(ai.packageName, ai.name));
                startActivitySafely(startIntent);

                return true;
            } else
                return super.onKeyDown(keyCode, event);
        }
    }

    private void startActivitySafely(Intent intent) {
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this, "null",
                    Toast.LENGTH_SHORT).show();
        } catch (SecurityException e) {
            Toast.makeText(this, "null",
                    Toast.LENGTH_SHORT).show();
        }
    }

//    private void registerBoardReceiver() {
//        manager = LocalBroadcastManager.getInstance(this);
//        IntentFilter filter = new IntentFilter();
//        filter.addAction(MESSAGE_UNREAD);
//        int aa = messageCount;
//        receiver = new BroadcastReceiver() {
//            @Override
//            public void onReceive(Context context, final Intent intent) {
//                //刷新消息的数量
//                int count = intent.getIntExtra("count", 0);
//                messageCount = messageCount - count;
//                under_Message_number.setText(String.valueOf(messageCount));
//            }
//        };
//        manager.registerReceiver(receiver, filter);
//    }

    public void unregisterBroadCastReceiver(){
        unregisterReceiver(receiver);
        unregisterReceiver(netReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterBroadCastReceiver();
//        //关闭服务
//        stopService(intent);
    }

    /*
        * 消息只能在再线加载，如果离线默认设置为0
        * */
    public void loadUserMassgeCount(){

        Map<String,Object> map=new HashMap<>();
        map.put("empid",id);
        map.put("task","loadNewMsgNum");
        pubClass.Post(pubClass.Server_namehzm, map,new pubClass.MyCallBack<String>(){

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                //判断传过来的数据类型，得到的数据解析后设置msg的个数
                String[] resArray=result.split("\\|");
                if (resArray[0].equals("200")) {
                    String[] resultMsg = resArray[3].split(",");
                    String[] yichang = resultMsg[0].split(":");
                    String[] xiaoxi = resultMsg[1].split(":");
                    String[] gonggao = resultMsg[2].split(":");
                    messageCount = Integer.parseInt(yichang[1]) + Integer.parseInt(xiaoxi[1]) + Integer.parseInt(gonggao[1]);
                    if (messageCount>0){
                        under_Message_number.setVisibility(View.VISIBLE);
                        if (messageCount>99){
                            under_Message_number.setText(String.valueOf(99));
                        }else{
                            under_Message_number.setText(String.valueOf(messageCount));
                        }
                    }else{
                        under_Message_number.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);

            }
        });
    }
    //下载头像信息
    public  void downloadFile( String url, String path) {
        final RequestParams requestParams = new RequestParams(url);
        requestParams.setSaveFilePath(path);
        x.http().get(requestParams, new Callback.ProgressCallback<File>() {
            @Override
            public void onWaiting() {
            }
            @Override
            public void onStarted() {
            }
            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
            }
            @Override
            public void onSuccess(File result) {
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(MainActivity.this,"头像加载失败", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onCancelled(CancelledException cex) {
            }
            @Override
            public void onFinished() {
            }
        });
    }
    public void setStatusBar(){
        //5.0使用metarDesign
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP){
            Window window = getWindow();
//取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//设置状态栏颜色
            window.setStatusBarColor(ContextCompat.getColor(this,R.color.blue));
            ViewGroup mContentView = (ViewGroup) findViewById(Window.ID_ANDROID_CONTENT);
            View mChildView = mContentView.getChildAt(0);
            if (mChildView != null) {
                //注意不是设置 ContentView 的 FitsSystemWindows, 而是设置 ContentView 的第一个子 View . 预留出系统 View 的空间.
                ViewCompat.setFitsSystemWindows(mChildView, true);
            }
        }
    }
    public void weatherUpdate(final String url, String desc, final int szie){
        MaterialDialogUtils.showTitleMaterialDialog(this, "版本更新", desc, "确定", "取消", true, new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                //开启下载
                if (NetWorkStateReceiver.netWorkType!=1){
                    MaterialDialogUtils.showMaterialDialog(MainActivity.this, "当前使用是移动网络，将消耗"+UpdateUtils.caluateSize(szie)+"流量，是否继续下载", "确定", "取消", true, false, new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            dialog.dismiss();
                            UpdateApi.getInstance().downLoadApk(MainActivity.this,url,pubClass.saveApkUrl);
                        }
                    }, new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            dialog.dismiss();
                        }
                    });
                }else{
                    UpdateApi.getInstance().downLoadApk(MainActivity.this,url,pubClass.saveApkUrl);
                }

            }
        }, new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

            }
        });
    }
    public void readVersionData(String url){
        try {
            OkHttpManger.getInstance().getAsync(url, new OKHttpUICallback.ResultCallback() {
                @Override
                public void onSuccess(String result) {
                    Log.e("versionResult",result);
                    if (result.contains("|")){
                        String[] res = result.split("\\|");
                        String version = res[0];
                        String downUrl = res[1];
                        int size;
                        if (res[2].contains("kb")){
                            String str = res[2].replace("kb","");
                            size = Integer.parseInt(str);
                        }else{
                            size = Integer.parseInt(res[2]);
                        }
                        String lcVersion = UpdateUtils.getVersion(MainActivity.this);
                        if (lcVersion.compareTo(version)<0){
                            //提示更新
                            weatherUpdate(downUrl,res[3],size);
                        }
                    }
                }
                @Override
                public void onError(Call call, IOException e) {
                    Toast.makeText(MainActivity.this,"服务器返回错误",Toast.LENGTH_SHORT).show();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }






}
